package by.sjc.grsu.service.impl;

import by.sjc.grsu.dao.repositiory.AccountDao;
import by.sjc.grsu.dao.repositiory.PaymentDao;
import by.sjc.grsu.dao.repositiory.PeriodicalsDao;
import by.sjc.grsu.dao.repositiory.SubscriptionsDao;
import by.sjc.grsu.model.Account;
import by.sjc.grsu.model.Payment;
import by.sjc.grsu.model.Subscription;
import by.sjc.grsu.service.SubscriptionsService;
import com.sun.org.apache.xalan.internal.lib.ExsltDatetime;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Service
public class SubscriptionsServiceImpl implements SubscriptionsService {
    public static final Logger logger = Logger.getLogger(SubscriptionsServiceImpl.class);

    @Autowired
    private SubscriptionsDao subscriptionsDao;
    @Autowired
    private AccountDao accountDao;
    @Autowired
    private PeriodicalsDao periodicalsDao;
    @Autowired
    private PaymentDao paymentDao;

    @Override
    public List<Subscription> getAccountSubscriptions(Account account) {
        return subscriptionsDao.findByAccountId(account.getId());
    }

    @Override
    public void disableSubscription(int subId) {
        Subscription sub = subscriptionsDao.findById(subId);
        sub.setEnabled(false);
        subscriptionsDao.update(sub);
    }

    @Override
    public void subscribe(int accountId, int periodicalId, int monthCount) {
        Subscription subscription = new Subscription();
        subscription.setAccount(accountDao.findById(accountId));
        subscription.setPeriodical(periodicalsDao.findById(periodicalId));
        subscription.setEnabled(true);
        Calendar cal = Calendar.getInstance();
        subscription.setStartDate(cal.getTime());
        cal.add(Calendar.MONTH, 1);
        subscription.setEndDate(cal.getTime());

        logger.info("subscribing="+subscription);
        subscriptionsDao.save(subscription);

    }

    @Override
    public int getSubscribeCost(int periodicalId, int monthCount) {
        return periodicalsDao.findById(periodicalId).getCost()*monthCount;
    }

    @Override
    public void registerPayment(Payment payment) {
        logger.info("register payment=" + payment);
        paymentDao.save(payment);
    }
}
